const {
  ipcMain,
  Notification,
  globalShortcut,
  app,
  Tray,
  Menu,
  nativeImage,
} = require("electron");
const hotkeyfunc = require("./hotkeyfunc");
const AutoStartManager = require("./autostart");
const {
  openDevTools,
  toggleFullscreen,
  refreshWindow,
  closeApp,
  minimizeWindow,
  restoreWindow,
  getStaticPath,
  execFileWay,
  refreshIgnoreCache,
  toggleChatroom,
  openWebViewTools,
} = hotkeyfunc;

// 导入工具函数
const {
  openExternalLink,
  downloadExternalFile,
  downloadBlobData,
  printFile,
  checkFileExists,
  openFileLocation,
  activeDownloads,
  readDownloadHistory,
  writeDownloadHistory,
} = require("./tools");

// 存储闪烁状态
let isFlashing = false;
let flashWindow = null;

/**
 * 监听消息，实现任务栏闪烁提醒
 */
function stopFlashing() {
  if (!isFlashing || !flashWindow) return;
  // 停止闪烁
  if (process.platform !== "darwin") {
    flashWindow.flashFrame(false);
  } else {
    app.dock.cancelBounce();
  }
  // 移除事件监听
  flashWindow.removeListener("focus", stopFlashing);
  flashWindow.removeListener("show", stopFlashing);
  // 重置状态
  isFlashing = false;
  flashWindow = null;
}
class UtilsClass {
  constructor(win, isDev) {
    this.mainWindow = win;
    this.isDevelopment = isDev;
    this.iconPath = getStaticPath(isDev, "image/favicon.ico");
    this.autoStartManager = new AutoStartManager();
  }

  getShotcuts(types = []) {
    const win = this.mainWindow;
    const isDev = this.isDevelopment;
    return [
      { key: "F11", action: () => toggleFullscreen(win), type: "local" },
      // 打开webview的控制台
      {
        key: "CommandOrControl+Shift+I",
        action: () => openWebViewTools(win),
        type: "local",
      },
      // 打开的是当前window的控制台
      {
        key: "CommandOrControl+Shift+E",
        action: () => openDevTools(win),
        type: "local",
      },
      {
        key: "CommandOrControl+R",
        action: () => refreshWindow(win),
        type: "local",
      },
      { key: "F5", action: () => refreshIgnoreCache(win), type: "local" },
      { key: "CommandOrControl+Q", action: () => closeApp(win), type: "local" },
      {
        key: "CommandOrControl+M",
        action: () => minimizeWindow(win),
        type: "local",
      },
      { key: "Ctrl+2", action: () => toggleChatroom(win), type: "local" },
      {
        key: "Ctrl+1",
        action: () => execFileWay.call(hotkeyfunc, isDev, win),
        type: "global",
      },
    ].filter((item) => types.includes(item.type));
  }

  isWindowVisible() {
    return (
      this.mainWindow &&
      !this.mainWindow.isMinimized() &&
      this.mainWindow.isVisible()
    );
  }

  taskbarFlashNotice(data) {
    // 如果窗口处于打开状态，则不发出任何提醒
    if (this.isWindowVisible()) return;
    // 如果已经在闪烁，不再重复启动
    if (isFlashing) return;
    flashWindow = this.mainWindow;
    isFlashing = true;
    // 开始闪烁,win/linux
    if (process.platform !== "darwin") {
      flashWindow.flashFrame(true);
      this.startTrayFlash();
      // 托盘闪烁
      this.mainWindow.webContents.send("tray-flash");
    } else {
      // mac
      app.dock.bounce("informational");
    }
    // 监听窗口焦点事件
    flashWindow.on("focus", () => {
      stopFlashing();
      this.stopTrayFlash();
    });
    flashWindow.on("show", () => {
      stopFlashing();
      this.stopTrayFlash();
    });
  }

  sendNotification(data) {
    // 如果窗口处于打开状态，只发出左下角通知提醒，未打开时闪烁任务栏
    if (!this.isWindowVisible()) {
      this.taskbarFlashNotice(data);
    }
    const notification = new Notification({
      title: "通知",
      body: data.message || data,
      icon: this.iconPath, // 图标路径
      silent: false, // 是否静音
    });
    notification.show();
    notification.on("click", () => {
      // 点击通知时执行的操作
      if (this.mainWindow.isMinimized()) {
        this.mainWindow.restore(); // 如果窗口是最小化状态，则恢复
      }
      this.mainWindow.focus();
    });
  }

  // 闪烁右小角小图标
  startTrayFlash() {
    if (this.tray && process.platform === "win32") {
      if (this.tray._flashTimer) return; // 避免多次定时器
      const iconPath1 = getStaticPath(this.isDevelopment, "image/favicon.ico");
      const iconPath2 = getStaticPath(
        this.isDevelopment,
        "image/favicon-empty.png"
      );
      let flag = false;
      this.tray._flashTimer = setInterval(() => {
        this.tray.setImage(
          nativeImage.createFromPath(flag ? iconPath1 : iconPath2)
        );
        flag = !flag;
      }, 500);
    }
  }

  // 停止闪烁右小角图标
  stopTrayFlash() {
    if (this.tray && this.tray._flashTimer) {
      clearInterval(this.tray._flashTimer);
      this.tray._flashTimer = null;
      const iconPath = getStaticPath(this.isDevelopment, "image/favicon.ico");
      this.tray.setImage(nativeImage.createFromPath(iconPath));
    }
  }

  // 最小化到托盘
  setMinimizeWindowToTray() {
    if (!this.tray) {
      const iconPath = getStaticPath(this.isDevelopment, "image/favicon.ico");
      this.tray = new Tray(nativeImage.createFromPath(iconPath));
      const contextMenu = Menu.buildFromTemplate([
        {
          label: "显示主界面",
          click: () => {
            this.mainWindow.show();
            this.stopTrayFlash();
          },
        },
        { type: "separator" },
        {
          label: "退出",
          click: () => {
            this.isQuiting = true;
            app.quit();
          },
        },
      ]);
      this.tray.setToolTip("项目管理");
      this.tray.setContextMenu(contextMenu);
      this.tray.on("click", () => {
        this.mainWindow.show();
        this.stopTrayFlash();
      });
    }
    this.mainWindow.hide();
  }

  // 注册全局快捷键
  registerShortcuts() {
    // 全局快捷键注册
    this.getShotcuts(["global"]).forEach(({ key, action }) => {
      const ret = globalShortcut.register(key, action);
      if (!ret) {
        console.error(`register global shortcut error: ${key}`);
      }
    });
  }

  // 注册局部快捷键
  registerLocalShortcutKeys() {
    this.getShotcuts(["local"]).forEach(({ key, action }) => {
      const ret = globalShortcut.register(key, action);
      if (!ret) {
        console.error(`register local shortcut error: ${key}`);
      }
    });
  }

  // 注册局部快捷键
  unRegisterLocalShortcutKeys() {
    this.getShotcuts(["local"]).forEach(({ key }) => {
      globalShortcut.unregister(key);
    });
  }

  registerIpcMainAfterAppReady() {
    // 接收iframe消息，唤醒任务栏闪烁
    ipcMain.on("electron-recive-message", (event, data) => {
      this.taskbarFlashNotice(data);
    });

    // 接收消息，发送系统通知
    ipcMain.on("electron-recive-notification", (event, data) => {
      this.sendNotification(data);
    });

    // 接收消息，开启截图操作
    ipcMain.on("electron-recive-screen-handle", (event, data) => {
      execFileWay.call(hotkeyfunc, this.isDevelopment, this.mainWindow, data);
    });

    ipcMain.handle("get-app-version", () => {
      return app.getVersion();
    });

    // 快捷键-截图
    ipcMain.on("hotkey-screenshot", () => {
      execFileWay.call(hotkeyfunc, this.isDevelopment, this.mainWindow);
    });

    // 快捷键-刷新F5
    ipcMain.on("hotkey-refresh-f5", () => {
      refreshIgnoreCache(this.mainWindow);
    });

    // 打开外部链接
    ipcMain.on("open-external-link", async (event, url, showDialog = false) => {
      await openExternalLink(this.mainWindow, url, showDialog);
    });

    // 下载外部文件
    ipcMain.on("download-external-file", async (event, { url, filename }) => {
      await downloadExternalFile(
        this.mainWindow,
        url,
        filename,
        getStaticPath,
        this.isDevelopment,
        (action, downloadId, data) => {
          // 发送进度更新到渲染进程
          this.mainWindow.webContents.send("download-progress", {
            action,
            downloadId,
            data,
          });
        }
      );
    });

    // 下载blob数据
    ipcMain.on("download-file", async (event, { data, filename, mimeType }) => {
      await downloadBlobData(
        this.mainWindow,
        data,
        filename,
        mimeType,
        getStaticPath,
        this.isDevelopment,
        (action, downloadId, data) => {
          // 发送进度更新到渲染进程
          this.mainWindow.webContents.send("download-progress", {
            action,
            downloadId,
            data,
          });
        }
      );
    });

    // 检查文件是否存在
    ipcMain.handle("check-file-exists", async (event, filePath) => {
      return checkFileExists(filePath);
    });

    // 打开文件位置
    ipcMain.on("open-file-location", async (event, filePath) => {
      openFileLocation(filePath);
    });

    // 打印
    ipcMain.on("webview-print-file", async (event, fileUrl) => {
      await printFile(fileUrl);
    });

    // 打开/关闭工具箱
    ipcMain.on("electron-recive-toggle-toolbox", (event, data) => {
      this.mainWindow.webContents.send("toggle-toolbox", data);
    });

    // 取消下载
    ipcMain.on("cancel-download", (event, downloadId) => {
      const task = activeDownloads.get(downloadId);
      if (task) {
        task.request.abort?.();
        task.writeStream.destroy?.();
        fs.unlink(task.filePath, () => {});
        activeDownloads.delete(downloadId);
      }
    });

    ipcMain.handle("read-download-history", () => {
      return readDownloadHistory();
    });
    ipcMain.handle("write-download-history", (event, history) => {
      writeDownloadHistory(history);
      return true;
    });
  }
}

module.exports = UtilsClass;
